var indicatorRoleDataForm = new Form();
var indicatorRoleRegultTable = new Table();
var indicatorRoleUnitTable = new Table();
var indicatorGroupTree = new Tree();
var indicatorButtomTable = new Table();
var indicatorAjax = new Ajax();
var condition = [];
var indicators = [];
var requestObjects = [];
var groupDialog = new Dialog();
var ajaxDatas = [];
var isSysAdmin = false;
var flag = false;

var company = {};
var _package = {};

$(function() {
	initScripts();
});
/** 初始化script * */
function initScripts() {
	isSysAdmin = sessionStorage.user_loginId == "sysadmin";
	flag = sessionStorage.orgCode == "*";

	loadScript(appPath
			+ "/project-yddemo/indicatorPackage/locale/IndicatorPackage_"
			+ appLocale + ".js"); // 1.加载国际化js*
	loadScript(appPath
			+ "/project-yddemo/indicatorRole/properties/IndicatorRoleProperties_Data.js"); // 2.加载配置js(非必配,配置也可写在本js中)
	loadScript(appPath
			+ "/project-yddemo/indicatorPackage/properties/IndicatorPackageProperties_Data.js"); // 2.加载配置js(非必配,配置也可写在本js中)

	loadScript(appPath + "/project-yddemo/indicator/locale/Indicator_"
			+ appLocale + ".js"); // 1.加载国际化js*
	loadScript(appPath + "/project-yddemo/indicator/locale/IndicatorGroup_"
			+ appLocale + ".js"); // 1.加载国际化js*
	loadScript(appPath
			+ "/project-yddemo/indicator/properties/IndicatorProperties.js");
	loadScript(appPath
			+ "/project-yddemo/indicator/properties/IndicatorGroupProperties.js");
}
function initSelectDiv() {
	indicatorRoleDataForm.initTableConditions({
		divId : "selectDiv",
		conditions : IndicatorRoleData.getConditionData()
	});
}
function initRegultDiv() {
	indicatorRoleRegultTable.initTable({
		divId : "regultDiv",
		columns : IndicatorRoleData.getColumsRegult()
	});
}
function initUnitDiv() {
	indicatorRoleUnitTable.initTable({
		divId : "unitDiv",
		columns : IndicatorRoleData.getColumsUnit(),
		dataAjax : {
			url : requestPath + "/yddemo/indicatorRoles/getUnits",
			type : "GET",
			data : {}
		},
		rowClickFun : function(datas) {
			resultsGenerator();
		}
	});
	indicatorRoleUnitTable.reloadData();
}
function initIndicatorGroupTree() {
	indicatorGroupTree
			.initTree({
				divId : "indicatorTreeDiv", // 归属div*
				ajaxType : "param", // ajax:初始化url/root_root,懒加载url/nodeId);
				root : {
					text : groupLocale.text.groupRoot,
					nodeId : "root_root",
					leaf : false,
					expanded : true
				},
				dataAjax : { // 数据源ajax*
					url : requestPath
							+ "/yddemo/indicatorGroupTree/getAllIndicator", // 请求url*
					async : false, // 是否异步*
					type : "GET", // 请求类型*
					params : condition,
					data : indicators
				},
				models : IndicatorPackageData.getTreeModels(indicators),
				align : { // 元素顺序
					left : "expand",
					center : "text",
					right : "check"
				},
				checkIcon : staticPath
						+ "/framework/default/img/Icon_tree_check.png", // 选中图标
				partcheckIcon : staticPath
						+ "/framework/default/img/Icon_tree_partcheck.png", // 部分选图标
				uncheckIcon : staticPath
						+ "/framework/default/img/Icon_tree_uncheck.png", // 未选图标
				expandIcon : staticPath
						+ "/framework/default/img/Icon_tree_expand.png", // 展开图标
				closeIcon : staticPath
						+ "/framework/default/img/Icon_tree_close.png", // 闭合图标
				textClickFun : function(nodeId) { // 文本单击事件*
					if (nodeId == "undefined") {
						nodeId = "root_root";
					}
					indicatorGroupTree.checkDefaultFun(nodeId);// 添加
					resultsGenerator();
				},
				expandFun : function(nodeId) { // 展开单击事件*
					if (nodeId == "undefined") {
						nodeId = "root_root";
					}
					indicatorGroupTree.expandDefaultFun(nodeId);

				},
				checkFun : function(nodeId) { // 选中单击事件*
					if (nodeId == "undefined") {
						nodeId = "root_root";
					}
					indicatorGroupTree.checkDefaultFun(nodeId);
					resultsGenerator();
				}
			});
}
function initButton() {
	indicatorButtomTable.initButtons({
		divId : "buttonDiv",
		buttons : IndicatorRoleData.getViewButtons()
	});
}
function save() {
	var resultJson = indicatorAjax.sendAjax({
		url : requestPath + "/yddemo/indicatorDetails", // 请求url*
		async : false, // 是否异步*
		type : "PUT", // 请求类型*
		data : requestObjects
	});
	if (resultJson.success) {
		groupDialog.tipDialog(indicatorLocale.text.addSuccess, function() {
			// window.parent.refreshIndicator(); //
			// 新增成功后,刷新父对象(刷新User_View.jsp页面)
			groupDialog.closeDialog(); // 新增成功后,关闭父对象弹出框(关闭User_Add.jsp页面)
		});
	} else {
		groupDialog.alertDialog(resultJson.message); // 新增失败后,父对象弹出警告框
	}
}
function resultsGenerator() {
	var regult = [];// 用于存储数据
	requestObjects = [];

	var units = indicatorRoleUnitTable.getSelectDatas();
	var tree = indicatorGroupTree.getCheckedNodes();
	var role = {
		"id" : sessionStorage.selectRole
	};
	for (var i = 0; i < units.length; i++) {
		for (var j = 0; j < tree.length; j++) {
			var data = {
				"indicatorName" : units[i].name + " " + tree[j].name
			};// 组成结果
			regult.push(data);
			var requestObject = {};
			var indicator = {
				"id" : tree[j].id
			}
			requestObject.company = company;
			requestObject.indicatorPackage = _package;
			requestObject.comUnit = units[i];
			requestObject.indicator = indicator;
			requestObject.dimension = $("[key='dimension']").val();
			requestObjects.push(requestObject);
		}
	}
	if (requestObjects.length == 0) {
		var requestObject = {};
		requestObject.company = company;
		requestObject.indicatorPackage = _package;
		requestObject.comUnit = units[i];
		requestObject.dimension = $("[key='dimension']").val();
		requestObjects.push(requestObject);
	}
	indicatorRoleRegultTable.removeDatas(indicatorRoleRegultTable.dataList);
	indicatorRoleRegultTable.addDatas(regult);
	indicatorRoleRegultTable.reloadData();
}

function setCondition() {
	condition = indicatorRoleDataForm.getFormConditions();
}
function initDatas(datas) {
	indicators=[];
	indicatorRoleRegultTable.removeDatas(indicatorRoleRegultTable.dataList);
	indicatorRoleRegultTable.reloadData();
	var node = indicatorPackageTree.getNode(datas);
	if (node.entityType == "Company") {
		sessionStorage.selectNodeId = datas;
	}
	if (node.entityType != "IndicatorPackageVoBean") {
		return;
	}
	

	var groupObj = indicatorAjax.sendAjax({ // 获取用户对象
		url : requestPath + "/yddemo/indicatorPackages/" + node.id, // 请求url*
		async : false, // 是否异步*
		type : "GET" // 请求类型*
	});
	company = groupObj.company;
	_package.id = groupObj.id;
	// 根据company 重新设置unit的值
	indicatorRoleUnitTable.removeDatas(indicatorRoleUnitTable.dataList);
	indicatorRoleUnitTable.initTable({
		divId : "unitDiv",
		columns : IndicatorRoleData.getColumsUnit(),
		dataAjax : {
			url : requestPath
					+ "/yddemo/indicatorDetails/findAllComUnitByCompany", // 请求url*
			async : false, // 是否异步*
			type : "GET", // 请求类型*
		},
		rowClickFun : function(datas) {
			resultsGenerator();
		}
	});
	indicatorRoleUnitTable.reloadData({
		"companyId" : groupObj.company.id
	});
	// //////////////////////根据company查询所有的detail

	$("[key='dimension']").val(groupObj.dimension);
	setCondition();
	initIndicatorGroupTree();

	var detail = indicatorAjax.sendAjax({
		url : requestPath + "/yddemo/indicatorDetails",
		async : false,
		type : "GET",
		data : {
			"companyId" : groupObj.company.id,
			"packageId" : node.id,
			"dimension" : $("[key='dimension']").val()
		}
	});

	indicators = (detail.map(function(item) {
		return item.indicator;
	}));
	indicators=unique(indicators);
	initIndicatorGroupTree();

	var unitIds = detail.map(function(item) {
		return item.comUnit.id;
	});
	indicatorRoleUnitTable.setSelectRows(unique(unitIds), true);

}

function groupPageQuery(nodeId) {
	var nodeObj;
	if (nodeId != "root_root" && nodeId != "undefined") {
		nodeObj = indicatorPackageTree.getNode(nodeId);
	} else {
		nodeObj = setRootNode();
	}

	sessionStorage.nodeId = nodeId;
	var entityType = nodeObj.entityType;

	if (nodeObj.entityType == "Company") {
		setElementsEnabled("yddemo:indicatorPackage:add", "button", true);
		$("[action='yddemo:indicatorPackage:add']").unbind("click").bind(
				"click", function() {
					addIndicatorPackage();
				});
		disableButton();

	} else {
		// setElementsEnabled("yddemo:indicatorPackage:add", "button", false);

	}
	if (nodeObj.leaf) {
		enableButton();
		// 是叶子,点击后触发右边指标显示的内容，并且控制按钮的可用状态
		if ("IndicatorPackageVoBean" == entityType) {
			sessionStorage._package = nodeObj.id;
		}
	}
}
function setRootNode() {
	var root = {};
	root.entityId = "root";
	root.entityType = "root";
	root.expanded = true;
	root.iconCls = "ApplicationViewTile";
	root.id = "root";
	root.leaf = false;
	root.nodeId = "root_root";
	root.nodePid = "";
	root.params = null;
	root.text = groupLocale.text.groupRoot;
	return root;
}
/**
 * 数组去重复
 * 
 * @param array
 * @returns
 */
function unique(array) {
	var n = {}, r = [], len = array.length, val, type;
	for (var i = 0; i < array.length; i++) {
		val = array[i];
		type = typeof val;
		if (!n[val]) {
			n[val] = [ type ];
			r.push(val);
		} else if (n[val].indexOf(type) < 0) {
			n[val].push(type);
			r.push(val);
		}
	}
	return r;
}